import {Config} from "./config.js";

class Token{
   constructor(){
      this.verifyUrl = Config.baseRequestUrl + 'token/verifytoken';
      this.userUrl = Config.baseRequestUrl + 'token/user'
   }
   //验证token是否有效
   verify(){
      var token = wx.getStorageSync('token');
      if(token){
         this.verifyTokenFromServer(token);
      }else{
         this.getTokenFromServer();
      }
   }
   //直接从服务器获取token
   getTokenFromServer(callback){
      let that = this;
      wx.login({
         success:function(res){
            wx.request({
               url: that.userUrl,
               method: 'post',
               data: {code: res.code},
               success:function(result){
                  wx.setStorageSync('token', result.data.token);
                  callback && callback(result.data.token);
               }
            })
         }
      })
   }
   //从服务器验证tiken是否合法
   verifyTokenFromServer(token){
      let that = this;
      wx.request({
         url: this.verifyUrl,
         method: 'post',
         data: {token:token},
         success:function(res){
            if(!res.data.isvalide){
               that.getTokenFromServer();
            }
         }
      })
   }
}
export {Token};